'use strict';

const Service = require('egg').Service;

class ReminderService extends Service {
  // 获取提醒列表
  async getList(userId, options = {}) {
    const { Op } = this.app.Sequelize;
    const { page = 1, pageSize = 20, type, status } = options;

    const where = { user_id: userId };
    
    if (type) {
      where.type = type;
    }
    
    if (status === 'completed') {
      where.is_completed = true;
    } else if (status === 'pending') {
      where.is_completed = false;
      where.is_active = true;
    } else if (status === 'overdue') {
      where.is_completed = false;
      where.is_active = true;
      where.reminder_date = {
        [Op.lt]: new Date()
      };
    }

    const result = await this.ctx.model.Reminder.findAndCountAll({
      where,
      include: [
        {
          model: this.ctx.model.Clothing,
          as: 'clothing',
          attributes: ['id', 'name', 'main_image']
        },
        {
          model: this.ctx.model.Outfit,
          as: 'outfit',
          attributes: ['id', 'name', 'main_image']
        }
      ],
      order: [['reminder_date', 'ASC']],
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    return {
      list: result.rows,
      total: result.count,
      page,
      pageSize
    };
  }

  // 创建提醒
  async create(reminderData) {
    const {
      type,
      title,
      description,
      clothing_id,
      outfit_id,
      reminder_date,
      repeat_type = 'none',
      repeat_interval = 1,
      priority = 'medium',
      metadata
    } = reminderData;

    const reminder = await this.ctx.model.Reminder.create({
      user_id: reminderData.user_id,
      type,
      title,
      description,
      clothing_id,
      outfit_id,
      reminder_date: new Date(reminder_date),
      repeat_type,
      repeat_interval,
      priority,
      metadata: metadata ? JSON.stringify(metadata) : null
    });

    return reminder;
  }

  // 更新提醒
  async update(id, userId, updateData) {
    const reminder = await this.ctx.model.Reminder.findOne({
      where: { id, user_id: userId }
    });

    if (!reminder) {
      throw new Error('提醒不存在');
    }

    await reminder.update(updateData);
    return reminder;
  }

  // 删除提醒
  async delete(id, userId) {
    const reminder = await this.ctx.model.Reminder.findOne({
      where: { id, user_id: userId }
    });

    if (!reminder) {
      throw new Error('提醒不存在');
    }

    await reminder.destroy();
    return true;
  }

  // 标记为已完成
  async markAsCompleted(id, userId) {
    const reminder = await this.ctx.model.Reminder.findOne({
      where: { id, user_id: userId }
    });

    if (!reminder) {
      throw new Error('提醒不存在');
    }

    await reminder.update({
      is_completed: true,
      completed_at: new Date()
    });

    // 如果是重复提醒，创建下一个提醒
    if (reminder.repeat_type !== 'none') {
      await this.createNextReminder(reminder);
    }

    return reminder;
  }

  // 获取今日提醒
  async getTodayReminders(userId) {
    const { Op } = this.app.Sequelize;
    const today = new Date();
    const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);

    const reminders = await this.ctx.model.Reminder.findAll({
      where: {
        user_id: userId,
        is_completed: false,
        is_active: true,
        reminder_date: {
          [Op.between]: [startOfDay, endOfDay]
        }
      },
      include: [
        {
          model: this.ctx.model.Clothing,
          as: 'clothing',
          attributes: ['id', 'name', 'main_image']
        },
        {
          model: this.ctx.model.Outfit,
          as: 'outfit',
          attributes: ['id', 'name', 'main_image']
        }
      ],
      order: [['priority', 'DESC'], ['reminder_date', 'ASC']]
    });

    return reminders;
  }

  // 创建洗涤提醒
  async createLaundryReminder(userId, data) {
    const { clothingId, reminderDate, notes } = data;

    // 获取衣服信息
    const clothing = await this.ctx.model.Clothing.findByPk(clothingId);
    if (!clothing) {
      throw new Error('衣服不存在');
    }

    const reminder = await this.create({
      user_id: userId,
      type: 'laundry',
      title: `洗涤提醒：${clothing.name}`,
      description: notes || `该洗涤 ${clothing.name} 了`,
      clothing_id: clothingId,
      reminder_date: reminderDate || this.calculateNextLaundryDate(clothing),
      repeat_type: 'weekly',
      repeat_interval: 1,
      priority: 'medium',
      metadata: {
        clothingType: clothing.category?.name,
        lastWorn: clothing.last_worn_date
      }
    });

    return reminder;
  }

  // 创建换季提醒
  async createSeasonalReminder(userId, data) {
    const { season, reminderDate, notes } = data;

    const seasonalTasks = {
      spring: '整理春季衣物，收纳冬季厚重衣物',
      summer: '准备夏季清爽衣物，收纳春季外套',
      autumn: '整理秋季衣物，准备保暖单品',
      winter: '整理冬季保暖衣物，收纳夏季衣物'
    };

    const reminder = await this.create({
      user_id: userId,
      type: 'seasonal',
      title: `${season}季换季提醒`,
      description: notes || seasonalTasks[season],
      reminder_date: reminderDate || this.calculateSeasonalDate(season),
      repeat_type: 'yearly',
      repeat_interval: 1,
      priority: 'high',
      metadata: {
        season,
        tasks: this.getSeasonalTasks(season)
      }
    });

    return reminder;
  }

  // 创建购物提醒
  async createShoppingReminder(userId, data) {
    const { items, reminderDate, budget, notes } = data;

    const reminder = await this.create({
      user_id: userId,
      type: 'shopping',
      title: '购物清单提醒',
      description: notes || `您有 ${items.length} 件商品待购买`,
      reminder_date: reminderDate || new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 默认7天后
      repeat_type: 'none',
      priority: 'medium',
      metadata: {
        items,
        budget,
        itemCount: items.length
      }
    });

    return reminder;
  }

  // 获取购物清单
  async getShoppingList(userId) {
    const shoppingItems = await this.ctx.model.ShoppingList.findAll({
      where: {
        user_id: userId,
        is_purchased: false
      },
      include: [{
        model: this.ctx.model.Category,
        as: 'category'
      }],
      order: [['priority', 'DESC'], ['created_at', 'ASC']]
    });

    // 按分类分组
    const groupedItems = {};
    shoppingItems.forEach(item => {
      const categoryName = item.category?.name || '其他';
      if (!groupedItems[categoryName]) {
        groupedItems[categoryName] = [];
      }
      groupedItems[categoryName].push(item);
    });

    // 计算统计信息
    const totalEstimatedPrice = shoppingItems.reduce((sum, item) => 
      sum + (parseFloat(item.estimated_price) || 0), 0
    );

    const priorityStats = {
      urgent: shoppingItems.filter(item => item.priority === 'urgent').length,
      high: shoppingItems.filter(item => item.priority === 'high').length,
      medium: shoppingItems.filter(item => item.priority === 'medium').length,
      low: shoppingItems.filter(item => item.priority === 'low').length
    };

    return {
      items: shoppingItems,
      groupedItems,
      statistics: {
        totalItems: shoppingItems.length,
        totalEstimatedPrice: totalEstimatedPrice.toFixed(2),
        priorityStats
      }
    };
  }

  // 更新购物清单
  async updateShoppingList(userId, items) {
    // 删除现有的购物清单项
    await this.ctx.model.ShoppingList.destroy({
      where: { user_id: userId, is_purchased: false }
    });

    // 创建新的购物清单项
    const createdItems = [];
    for (const item of items) {
      const shoppingItem = await this.ctx.model.ShoppingList.create({
        user_id: userId,
        ...item
      });
      createdItems.push(shoppingItem);
    }

    return createdItems;
  }

  // 创建下一个重复提醒
  async createNextReminder(reminder) {
    const nextDate = this.calculateNextReminderDate(reminder.reminder_date, reminder.repeat_type, reminder.repeat_interval);
    
    if (nextDate) {
      await this.create({
        user_id: reminder.user_id,
        type: reminder.type,
        title: reminder.title,
        description: reminder.description,
        clothing_id: reminder.clothing_id,
        outfit_id: reminder.outfit_id,
        reminder_date: nextDate,
        repeat_type: reminder.repeat_type,
        repeat_interval: reminder.repeat_interval,
        priority: reminder.priority,
        metadata: reminder.metadata
      });
    }
  }

  // 计算下一个提醒日期
  calculateNextReminderDate(currentDate, repeatType, interval) {
    const date = new Date(currentDate);
    
    switch (repeatType) {
      case 'daily':
        date.setDate(date.getDate() + interval);
        break;
      case 'weekly':
        date.setDate(date.getDate() + (7 * interval));
        break;
      case 'monthly':
        date.setMonth(date.getMonth() + interval);
        break;
      case 'yearly':
        date.setFullYear(date.getFullYear() + interval);
        break;
      default:
        return null;
    }
    
    return date;
  }

  // 计算下次洗涤日期
  calculateNextLaundryDate(clothing) {
    const now = new Date();
    const lastWorn = clothing.last_worn_date ? new Date(clothing.last_worn_date) : now;
    
    // 根据衣服类型确定洗涤周期
    const laundryIntervals = {
      '内衣': 1,      // 1天
      '袜子': 1,      // 1天
      'T恤': 2,       // 2天
      '衬衫': 3,      // 3天
      '牛仔裤': 7,    // 7天
      '外套': 14,     // 14天
      '大衣': 30      // 30天
    };
    
    const categoryName = clothing.category?.name || 'T恤';
    const interval = laundryIntervals[categoryName] || 7;
    
    const nextDate = new Date(lastWorn);
    nextDate.setDate(nextDate.getDate() + interval);
    
    return nextDate;
  }

  // 计算季节性提醒日期
  calculateSeasonalDate(season) {
    const now = new Date();
    const year = now.getFullYear();
    
    const seasonalDates = {
      spring: new Date(year, 2, 1),  // 3月1日
      summer: new Date(year, 5, 1),  // 6月1日
      autumn: new Date(year, 8, 1),  // 9月1日
      winter: new Date(year, 11, 1)  // 12月1日
    };
    
    let targetDate = seasonalDates[season];
    
    // 如果今年的日期已过，设置为明年
    if (targetDate < now) {
      targetDate.setFullYear(year + 1);
    }
    
    return targetDate;
  }

  // 获取季节性任务
  getSeasonalTasks(season) {
    const tasks = {
      spring: [
        '收纳冬季厚重衣物',
        '整理春季轻薄衣物',
        '检查春季外套',
        '准备春季鞋子'
      ],
      summer: [
        '收纳春季外套',
        '整理夏季清爽衣物',
        '准备防晒衣物',
        '检查夏季鞋子'
      ],
      autumn: [
        '收纳夏季衣物',
        '整理秋季衣物',
        '准备保暖外套',
        '检查秋季靴子'
      ],
      winter: [
        '收纳秋季衣物',
        '整理冬季保暖衣物',
        '准备厚重外套',
        '检查冬季靴子'
      ]
    };
    
    return tasks[season] || [];
  }
}

module.exports = ReminderService;
